package com.tianji.learning.mq;

import cn.hutool.core.util.ObjectUtil;
import com.tianji.api.dto.trade.OrderBasicDTO;
import com.tianji.common.constants.MqConstants;
import com.tianji.learning.service.ILearningLessonService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import static com.tianji.common.constants.MqConstants.Exchange.ORDER_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.ORDER_PAY_KEY;
import static org.springframework.amqp.core.ExchangeTypes.TOPIC;

@Slf4j
@Component
@RequiredArgsConstructor
public class LessonChangeListener {
    private final ILearningLessonService lessonService ;
    /**
     * 监听订单支付或课程报名的消息
     *
     * @param order 订单信息
     */
//定义消息消费者参数交换机与队列绑定
    @RabbitListener(bindings = @QueueBinding
            (value = @Queue(value = "learning.lesson.queue", durable = "true"),
                    exchange = @Exchange(name = ORDER_EXCHANGE, type = TOPIC),
                    key = ORDER_PAY_KEY))
    public void listenLessonPay(OrderBasicDTO order) {
        //健壮性判断,判断是否为空
        if (order == null || order.getOrderId() == null || ObjectUtil.isEmpty(order.getCourseIds())) {
            log.error("订单信息为空，无法更新课程状态");
        }
        //数据存在，调用方法添加课程
        log.info("订单支付成功，更新课程状态");
        lessonService.addUserLessons(order.getUserId(), order.getCourseIds());
    }
}
